import requests
from lxml import etree
from flask import Flask, render_template, request

app = Flask(__name__)


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/search_mobile")
def search_mobile():
    phone = request.args.get("phone")
    data = get_mobile_info(phone)
    print(f'手机号信息:{data}')
    return render_template("index.html", data=data)


def get_mobile_info(phone):
    # 发送请求的地址
    url = f"https://ip138.com/mobile.asp?mobile={phone}&action=mobile"
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
    }
    response = requests.get(url, headers=headers)
    response.encoding = "utf-8"

    tree = etree.HTML(response.text)
    # 卡号归属地
    location_list = tree.xpath("//tr/td[2]/span/text()")
    # 若列表不为空，取第一个元素；否则设为空字符串
    location = location_list[0] if location_list else ""

    # 正文
    info_list = tree.xpath("//tr/td[2]/a[1]/text()")
    data={}
    data["phone"]=phone
    if info_list:
        data["location"]=location
        data["operator"]=info_list[1]
        data["area_code"]=info_list[2]
        data["post_code"]=info_list[3]

    return data

app.run(debug=True)
